package com.example.springsecurity;

import com.example.springsecurity.common.config.RedisCache;
import com.example.springsecurity.common.config.SystemUserLoginDetail;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;

import static com.example.springsecurity.common.constant.Constant.REDIS_LOGIN_PATH;

/**
 * @Description：安全认证管理框架项目启动类
 * @Author：fengcheng
 * @Date：2024/12/18 15:13
 */
@EnableScheduling
@SpringBootApplication
@MapperScan("com.example.springsecurity.mapper")
public class SpringSecurityApplication {

    @Resource
    private RedisCache redisCache;

    public static void main(String[] args) {
        SpringApplication.run(SpringSecurityApplication.class, args);
        System.out.println();
        System.out.println();
        System.out.println("安全认证管理项目 SpringSecurityApplication 启动成功！");
        System.out.println("系统默认登陆账号：18888888888，密码：123456");
        System.out.println("系统接口文档访问地址：http://localhost:48080/doc.html");
        System.out.println();
        System.out.println();
    }

    /**
     * @Description：系统停止前删除用户登录信息
     * @Author：fengcheng
     * @Date：2025/1/17 10:06
     * @ParamsType：[]
     * @Return：void
     */
    @PreDestroy
    public void destroy() {
        // 删除用户登录信息
        //获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            SystemUserLoginDetail sysUser = (SystemUserLoginDetail) authentication.getPrincipal();
            String mobile = sysUser.getSystemUser().getMobile();
            // 清除SecurityContextHolder中的用户信息
            SecurityContextHolder.getContext().setAuthentication(null);
            //删除redis中的值
            redisCache.deleteObject(REDIS_LOGIN_PATH + mobile);
        }
        System.out.println();
        System.out.println();
        System.out.println("安全认证管理项目 SpringSecurityApplication 停止成功！");
        System.out.println();
        System.out.println();
    }
}
